//
//  HWDRegistViewController.m
//  Demo
//
//  Created by 龚碧容 on 2017/9/18.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMRegistViewController.h"
#import "QLMRegisterUserNameVC.h"
#import "QLMDetailAddressVC.h"

#define NUM @"0123456789"
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

@interface QLMRegistViewController ()<UITextFieldDelegate>
@property (nonatomic,assign)BOOL agreeBool;
@end

@implementation QLMRegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title=self.titleStr;
    self.view.backgroundColor=[UIColor whiteColor];
    self.navigationController.navigationBarHidden=NO;
    _inviteTipLa.font=[UIFont systemFontOfSize:16];
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"我已阅读同意小马快修《用户使用协议》"];
    [str addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xf5c407) range:NSMakeRange(10,[str length]-10)];
    [_agreeButon setAttributedTitle:str forState:UIControlStateNormal];
    _agreeBool=YES;
    [self.agreeButon setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateNormal];
    self.verifyButton.titleLabel.font=[UIFont systemFontOfSize:13];
    
    [self.nameTextfield addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [self.repeatTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    self.registeView.backgroundColor=[UIColor whiteColor];
    
    self.comfirmButton.backgroundColor=kButtonColor;
    [self.zhanghaoLgButton setTitleColor:UIColorFromRGB(0xecb60f) forState:UIControlStateNormal];
    
    CGFloat nicknameOriginY=self.nicknameTF.frame.size.height+self.nicknameTF.frame.origin.y;
    CGFloat nameOriginY=self.nameTextfield.frame.size.height+self.nameTextfield.frame.origin.y;
    CGFloat verifyOriginY=self.verifyCodeTextfield.frame.size.height+self.verifyCodeTextfield.frame.origin.y;
    CGFloat passportOriginY=self.passportTextField.frame.size.height+self.passportTextField.frame.origin.y;
    CGFloat repeatOriginY=self.repeatTextField.frame.size.height+self.repeatTextField.frame.origin.y;
    
    NSArray *lineFrameArray=[NSArray arrayWithObjects:@(nicknameOriginY),@(nameOriginY),@(verifyOriginY),@(passportOriginY),@(repeatOriginY),nil];
    
    for (int i=0; i<lineFrameArray.count; i++) {
        UIView *lineView=[[UIView alloc] init];
        lineView.backgroundColor=[UIColor lightGrayColor];
        lineView.frame=CGRectMake(20, [lineFrameArray[i] floatValue]+5, kScreen_width-20*2, 0.5);
        [self.registeView addSubview:lineView];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent=NO;
    if ([self.titleStr isEqualToString:@"找回密码"]) {
        
        self.repeatTextField.placeholder=@"请重复输入密码";
        self.repeatTextField.secureTextEntry=YES;
        [self.comfirmButton setTitle:@"确定" forState:UIControlStateNormal];
        
        self.zhanghaoLgButton.hidden=YES;
        self.agreeButon.hidden=YES;
        self.registerTopCons.constant=0;
    }else{
        
        self.nameTextfield.hidden=NO;
        self.repeatTextField.placeholder=@"邀请码（选填）";
        self.repeatTextField.secureTextEntry=NO;
        [self.comfirmButton setTitle:@"注册" forState:UIControlStateNormal];
        
        self.zhanghaoLgButton.hidden=NO;
        self.agreeButon.hidden=NO;
        self.registerTopCons.constant=0;
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)textFieldDidChange:(UITextField *)textField{
    if (textField == _nameTextfield||textField == _repeatTextField) {
        if (textField.text.length > 11) {
            UITextRange *markedRange = [textField markedTextRange];
            if (markedRange) {
                return;
            }
            NSRange range = [textField.text rangeOfComposedCharacterSequenceAtIndex:11];
            textField.text = [textField.text substringToIndex:range.location];
        }
    }
}

#pragma mark - Action

- (IBAction)showDecriptionViewAction:(UIButton *)sender{
    QLMDetailAddressVC *webVC=[QLMDetailAddressVC new];
    webVC.htmlurlStr=[NSString stringWithFormat:@"%@/html/phone/agreement.html",kBaseURL];
    webVC.title=@"用户使用协议";
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:webVC animated:YES];
}

- (IBAction)agreeButtonAction:(id)sender {
    if (_agreeBool) {
        _agreeBool=NO;
        [self.agreeButon setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
    }else{
        _agreeBool=YES;
        [self.agreeButon setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateNormal];
    }
}

- (IBAction)zhanghaoLgAction:(id)sender{
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)verifyAction:(id)sender {
    
    [self hideKeyBoardAction];
    if ([_nameTextfield.text length]==0) {
        ETToast(@"请输入手机号");
        return;
    }
    
    __block NSInteger time = 119; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮的样式
                [self.verifyButton setTitle:@"重新发送" forState:UIControlStateNormal];
                [self.verifyButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
                self.verifyButton.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 120;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮显示读秒效果
                [self.verifyButton setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
                [self.verifyButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                self.verifyButton.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    [dic setObject:_nameTextfield.text forKey:@"phoneNumber"];
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/smsCode" withParamers:dic andBody:nil
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            ETToast(responseObject[@"msg"]);
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (IBAction)comfirmAction:(id)sender {
    
    [self hideKeyBoardAction];
    if (_nicknameTF.text.length==0) {
        ETToast(@"请输入姓名");
        return;
    }else if (_nameTextfield.text.length!=11) {//[ClientTool isMobileValid:_nameTextfield.text]
        ETToast(@"请输入正确的手机号码");
        return;
    }else if ([_verifyCodeTextfield.text length]==0) {
        ETToast(@"请输入验证码");
        return;
    }else if (![ClientTool judgePassWordLegal:_passportTextField.text]) {
        ETToast(@"请输入至少6位字母和数字组合的密码");
        return;
    }
    
    NSString *urlpathStr=nil;
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];

    urlpathStr=@"/auth/validRegister";
    
    if (_repeatTextField.text.length==0) {
        [dic setObject:@"" forKey:@"invitationCode"];
    }else{
        [dic setObject:_repeatTextField.text forKey:@"invitationCode"];
    }
    
    if (!_agreeBool) {
        ETToast(@"您需要选择同意用户使用协议才能注册");
        return;
    }
    
    [dic setObject:_nicknameTF.text forKey:@"userName"];
    [dic setObject:_nameTextfield.text forKey:@"phoneNumber"];
    [dic setObject:_verifyCodeTextfield.text forKey:@"code"];
    [dic setObject:[ClientTool md5:_passportTextField.text] forKey:@"password"];

    [self.view makeToastActivity:CSToastPositionCenter];

    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPathAndFormData:@"/auth/register" withParamers:dic andBody:nil
                               success:^(id responseObject){
                                   [self.view hideToastActivity];
                                   NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                                   if (code == 1) {
                                       ETToastWithDelay(@"恭喜您，注册成功！", 1);
                                       [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(delayShowProHud) userInfo:nil repeats:NO];
                                   }else{
                                       ETToast(responseObject[@"msg"]);
                                   }
                               }failure:^(NSError *error){
                                   [self.view hideToastActivity];
                                   ETToast(@"服务器连接失败");
                               }
     ];
}

- (void)delayShowProHud{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)hideKeyBoardAction{
    [self.nameTextfield resignFirstResponder];
    [self.verifyCodeTextfield resignFirstResponder];
    [self.passportTextField resignFirstResponder];
    [self.repeatTextField resignFirstResponder];
}

#pragma mark - UITextField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if([textField isEqual:self.passportTextField]){
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
    }
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
